import Snake from "./snake";
import Food from "./food";
import ScorePanel from "./score-panel";

class GameControl {
  snake: Snake;
  food: Food;
  scorePanel: ScorePanel;

  direction: string = "";
  isLive = true;

  constructor() {
    this.snake = new Snake();
    this.food = new Food();
    this.scorePanel = new ScorePanel(10, 5);

    this.init();
  }

  // 游戏初始化
  init() {
    document.addEventListener("keydown", this.keydownHandler.bind(this));
    this.run();
  }

  keydownHandler(event: KeyboardEvent) {
    this.direction = event.key;
  }

  run() {
    let X = this.snake.X;
    let Y = this.snake.Y;
    switch (this.direction) {
      case "ArrowUp":
      case "Up":
      case "w":
        // 向上移动
        Y -= 10;
        break;
      case "ArrowDown":
      case "Down":
      case "s":
        // 向下移动
        Y += 10;
        break;
      case "ArrowLeft":
      case "Left":
      case "a":
        // 向左移动
        X -= 10;
        break;
      case "ArrowRight":
      case "Right":
      case "d":
        // 向右移动
        X += 10;
        break;
    }

    this.checkEat(X, Y)

    try {
      this.snake.X = X;
      this.snake.Y = Y;
    } catch (err: any) {
      this.isLive = false;
      if (confirm(err.message + " GAME OVER!")) {
        location.reload()
      }
    }

    this.isLive &&
      setTimeout(this.run.bind(this), 300 - (this.scorePanel.level - 1) * 30);
  }

  checkEat(X: number, Y: number) {
    if (X === this.food.X && Y === this.food.Y) {
      this.food.change();
      this.scorePanel.addScore();
      this.snake.addBody();
    }
  }
}

export default GameControl;
